<?php
/**
 * standard function collection
 *
 * PHP version 5
 *
 * @category  PHP
 * @package   PHPMY
 * @author    Sven Ruttloff, www.sruttloff.de <service@sruttloff.de>
 * @copyright 2010 Sven Ruttloff, www.sruttloff.de
 * @license   http://www.sruttloff.de/cms/files/licence_en_lgpl.txt LGPL
 * @version   SVN: $Id: standard.inc.php 134 2010-11-25 11:53:49Z sruttloff@googlemail.com $
 * @link      phpmy
 */

/**
 * Send a Redirect HEADER to the browser
 *
 * @param string $target redirect target
 *
 * @return void script dies at function end!
 */
function redirect($target = '')
{
    if (!$target)
        $target = $_SERVER['REQUEST_URI'];
    // add SID
    if (SID)
    {
        // check if a var is in url
        if (preg_match("=\?=", $target))
        $target .= "&".SID;
        else
        $target .= "?".SID;
    }
    header("Location: $target");
    exit;
}

/**
 * Delete a folder from fs
 *
 * @param string $dir       complete dir path to empty
 * @param int    $subthread if 0 given dir will be deleted too
 *
 * @return bool
 */
function killDir($dir, $subthread = 0)
{
    if ($open = @opendir($dir))
    {
        while ($file = readdir($open))
        {
            if ($file != "." && $file != "..")
            {
                $newdir = $dir . "/" . $file;
                if (is_dir($newdir))
                {
                    killDir($newdir, 1);
                    if (!rmdir($newdir))
                        return false;
                }
                else
                    @unlink($newdir);
            }
        }
        closedir($open);
        if (!$subthread)
            if (!rmdir($dir))
                return false;
    }
    else
        return false;
    return true;
}
/**
 * return a get or post variable, in the order get, post
 *
 * @param string $var variable name
 *
 * @return mixed content of $var
 */
function sendvar($var = '')
{
    if (isset($_POST[$var]))
        return $_POST[$var];
    if (isset($_GET[$var]))
        return $_GET[$var];
    return false;
}
/**
 * return a stripped get or post variable, in the order get, post
 *
 * @param string $var variable name
 *
 * @return mixed content of $var
 */
function stripSendvar($var = '')
{
    return stripslashes(sendvar($var));
}
/**
 * add slashes to array values
 *
 * @param array $var array to add slashes in values
 *
 * @return array slash added values
 */
function addslashesSendvarArray ($var)
{
    foreach ($var as $k=>$v)
    {
        if (is_array($v))
            $var[$k] = addslashesSendvarArray($v);
        else
            $var[$k] = addslashes($v);
    }
    return $var;
}
/**
 * secure post and get vars
 *
 * @return void
 */
function secureVars ()
{
    if (isset($_POST))
    {
        foreach ($_POST as $k=>$v)
        {
            if (is_array($v))
                $_POST[$k] = addslashesSendvarArray($v);
            else
                $_POST[$k] = addslashes($v);
        }
    }
    if (isset($_GET))
    {
        foreach ($_GET as $k=>$v)
        {
            if (is_array($v))
                $_GET[$k] = addslashesSendvarArray($v);
            else
                $_GET[$k] = addslashes($v);
        }
    }
}
/**
 * sets a get and post variable
 *
 * @param string $name   name of the var
 * @param string $val    content of the var
 * @param string $target p|g|null(default) store in post, get or all
 *
 * @return bool
 */
function sendvarSet($name, $val = '', $target = null)
{
    switch (strtolower($target))
    {
        case 'p':
            $_POST[$name] = $val;
            break;
        case 'g':
            $_GET[$name] = $val;
            break;
        default:
            $_POST[$name] = $_GET[$name] = $val;
            break;
    }
    return true;
}
/**
 * check if a get and post variable is set, order is POST, GET
 *
 * @param string $var name of the var
 *
 * @return bool
 */
function issetSendvar($var)
{
    if ($var == '')
        return false;
    if (isset($_POST[$var]))
        return true;
    elseif (isset($_GET[$var]))
        return true;
    else return false;
}
/**
 * unset sendvar
 *
 * @param string $var name of the var
 *
 * @return void
 */
function unsetSendvar($var)
{
    if ($var == '')
        return;
    if (isset($_POST[$var]))
        unset($_POST[$var]);
    if (isset($_GET[$var]))
        unset($_GET[$var]);;
    return;
}
/**
 * Checks a given email adress for validity
 *
 * @param string $email email adress
 *
 * @return bool
 */
function checkMail($email)
{
    $valid = "^([a-z0-9_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,4}$";
    if (eregi($valid, $email))
        return true;
    else
        return false;
}
/**
 * Checks a given string for numbers only
 *
 * @param string $string check if nums only inside
 *
 * @return bool
 */
function checkNumsOnly($string = '')
{
    $valid = "=^[0-9]+$=s";
    return preg_match($valid, $string);
}
/**
 * Create a directory
 *
 * @param string $path  path
 * @param mixed  $chmod false or a CHMOD as strin
 *
 * @return bool
 */
function createDir($path, $chmod = false)
{
    if (is_dir($path))
        return true;
    if ($chmod)
        return mkdir($path, intval($chmod, 8));
    else
        return mkdir($path);
}
/**
 * Create a file with or without a CHMOD
 *
 * @param string $file    filename including absolute path
 * @param string $content file content
 * @param string $chmod   CHMOD of the file
 * @param int    $length  max file length
 *
 * @return bool
 */
function createFile($file = '', $content = '', $chmod = null, $length = 0)
{
    if (!$fp = fopen($file, 'w+'))
        return false;
    else
    {
        if ($length)
            fwrite($fp, $content, $length);
        else
            fwrite($fp, $content);
        fclose($fp);
        if ($chmod)
            chmod($file, intval($chmod, 8));
    }
    return true;
}
/**
 * copies file from source to target, keeps also symlinks!
 *
 * @param string $source    source file
 * @param string $target    target file
 * @param bool   $overwrite true = overwrite
 * @param string $chmod     CHMOD of file
 *
 * @return bool
 */
function copyFile($source, $target, $overwrite = false, $chmod = null)
{
    //check if target exists
    if (file_exists($target))
    {
        //overwrite ?
        if ($overwrite)
        {
            if (!@unlink($target))
                return "&09";
        } else
            return "&10";
    }
    // check if is symlink
    if (is_link($source))
    {
        // its a link
        $source =  readlink($source);
        // create symlink
        if (symlink($source, $target))
            return true;
        else
            return false;
    }
    else
    {
        if (!file_exists($source))
        {
            trigger_error(__FILE__. ' - copyFile: source does not exist: ' . $source, E_USER_ERROR);
            return false;
        }
        if (!@copy($source, $target))
            return false;
    }
    if ($chmod)
        @chmod($target, intval($chmod, 8));
    return true;
}
/**
 * replaces newline to <br /> if no new line HTML Tags are used in text
 *
 * @param string $text text
 *
 * @return string HTML Formated text
 */
function iNl2br($text)
{
    if (!preg_match("=(<br>|<br/>|<br />|</td>|</tr>|</p>|</div>)=siU", $text))
        return nl2br($text);
    else
        return $text;
}
/**
 * returns the referer
 *
 * @return mixed false if no referer else the referer
 */
function refererinfo()
{
    if (!$_SERVER['HTTP_REFERER'])
        return false;
    return parse_url($_SERVER['HTTP_REFERER']);
}
/**
 * returns the actual time as microtime
 *
 * @return float
 */
function getMicrotime()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float) $usec + (float) $sec);
}
/**
 * returns the formated filesize
 *
 * @param int $size filesize in bytes
 *
 * @return string filesize in KB,MB or GB
 */
function humanReadableFilesize($size)
{
    if ($size < 1024)
        $result = $size . ' Byte';
    else
    {
        $result = round($size / 1024, 2);
        if ($result < 1024)
            $result .= ' KB';
        else
            $result = round($result / 1024, 2) . ' MB';
        if ($result > 1024)
            $result = round($result / 1024, 2) . ' GB';
    }
    return $result;
}
/**
 * error handler
 *
 * @param string $errno   error number
 * @param string $errstr  error text
 * @param string $errfile file of error
 * @param string $errline line of error
 *
 * @return void
 */
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    /*	Bitwert	Konstante
     1	E_ERROR
     2	E_WARNING
     4	E_PARSE
     8	E_NOTICE
     16	E_CORE_ERROR
     32	E_CORE_WARNING
     64	E_COMPILE_ERROR
     128	E_COMPILE_WARNING
     256	E_USER_ERROR
     512	E_USER_WARNING
     1024	E_USER_NOTICE
     2047	E_ALL
     2048	E_STRICT
     */

    switch ($errno)
    {
        case "2" :
        case "8" : // notiz
        case "2048" :
            return;
            $message = "Error no.: $errno\n"
                . "File: " . basename($errfile) . " #" . "Line: $errline\n" . "Error text: $errstr\n";
            echo nl2br($message);
            break;
        default :
            $raw = debug_backtrace();
            $output="";
            foreach ($raw as $entry)
            {
                $output.="\nFile: "
                    . (isset($entry['file']) ?
                    $entry['file'] : '-')." (Line: " . (isset($entry['line']) ? $entry['line'] : '-') . ")\n";
                $output.="Function: ".$entry['function']."\n";
                if (isset($entry['args']))
                {
                    $output.="Args: " . cmsrFEErrorHandlerHelper($entry['args']) .  "\n";
                }
            }
            $message = "Error no.: $errno\n"
                . "File: " . basename($errfile) . "\n" . "Line: $errline\n" . "Error text: $errstr\n";
            $message .= "\nBacktrace:\n" . $output;
            echo nl2br($message);
            break;
    }
}
/**
 * exception handler - trigger error handler
 *
 * @param string $e error text
 *
 * @return void
 */
function myExceptionHandler ($e = null)
{
    trigger_error($e->getMessage(), E_USER_ERROR);
}
/**
 * helper of error handler
 *
 * @param mixed $args arguments to run
 *
 * @return string readable text of args
 */
function cmsrFEErrorHandlerHelper ($args)
{
    $output = '';
    foreach ($args as $arg)
    {
        if ($output)
        $output .= ', ';
        switch (true)
        {
            case is_array($arg) :
                $arg = 'array:' . cmsrFEErrorHandlerHelper($arg);
                break;
            case is_object($arg) :
                $arg = 'Class:' . get_class($arg);
                break;
            default:
                break;
        }
        $output .=  $arg;
    }
    return $output;
}
/**
 * Return browse elements
 *
 * @param int $totaldatas  quantity of datas to browse
 * @param int $limit       display limit (default: 10)
 * @param int $active      active element
 * @param int $maxelements maximum browse elements (default: 10)
 *
 * @return array array with numbered Elements
 */
function browseDatas($totaldatas = 0, $limit = 10, $active = 0, $maxelements = 10)
{
    $rewind = $forward = $offsets = array ();
    if (!$active)
        $active = 0;
    // rewind an forward elements
    if ($active)
    {
        $offsets = array(htmlentities('<') => 0, htmlentities('<<') => ($active - $limit));
        $maxelements += count($offsets);
    }
    // calc. how many pages we have
    $possiblepages =  floor(($totaldatas-1) / $limit);
    for ($i = 0; $i <= $possiblepages; $i++)
    {
        if (count($offsets) >= $maxelements)
            break;
        if (($i +1) < $possiblepages - $maxelements +3
            && ($i +1) < ($active / $limit) - (($maxelements -5) / 2)
        )
        {
             continue;
        }
        $offsets[($i +1)] = $i * $limit;
    }
    if ($active / $limit < $possiblepages)
    {
        $offsets[htmlentities('>>')] = ($active + $limit);
        $offsets[htmlentities('>')] = (integer) ($totaldatas / $limit) * $limit;
    }
    return count($offsets) > 1 ? $offsets : array ();
}
/**
 * Better var_dump, echo of var and content
 *
 * @param mixed $mixed variable to dump
 *
 * @return void
 */
function debugVar($mixed)
{
    echo '<pre>';
    var_dump($mixed);
    echo '</pre>';
    return;
}
/**
 * return the extension of a file
 *
 * @param string $filename filename
 *
 * @return string file extension
 */
function fileExtension ($filename = null)
{
    preg_match("=\.(\w*)$=i", $filename, $temp);
    return $temp[1];
}
/**
 * return a unique password
 *
 * @param int $number password length
 *
 * @return string password
 */
function createPassword($number = 4)
{
    $zeichen = "qwertzupasdfghkyxcvbnm";
    $zeichen .= "123456789";
    $zeichen .= "WERTZUPLKJHGFDSAYXCVBNM";
    srand((double) microtime() * 1000000);
    for ($i = 0; $i < $number; $i++)
    {
        $password .= substr($zeichen, (rand() % (strlen($zeichen))), 1);
    }
    return $password;
}
/**
 * return a quotet string
 *
 * @param string $text text to quote
 *
 * @return string
 */
function savePrint($text = null)
{
    echo HtmlFormat($text);
}
/**
 * returns a html string
 *
 *@param string $string text to convert
 *
 *@return string
 */
function htmlFormat($string = null)
{
    return htmlentities($string, ENT_QUOTES, 'UTF-8');
}
/**
 * returns a non html valid string
 *
 *@param string $string text to convert
 *
 *@return string
 */
function unHtmlFormat($string = null)
{
    return html_entity_decode($string, ENT_QUOTES, "UTF-8");
}
/**
 * convert arbitrary num values to formated values with its own fp separator
 *
 * @param float  $value     number to format
 * @param int    $places    how many nums after separator
 * @param string $returnsep comma separator (default = ,)
 *
 * @return string
 */
function curFormat($value = 0, $places = 2, $returnsep = ',')
{
    return str_replace('.', $returnsep, sprintf('%01.' . $places . 'f', str_replace(',', '.', $value)));
}
/**
 * convert multibyte strings (utf-8) and unserialize it
 *
 *@param string $serial_str serialized var
 *
 *@return mixed var
 */
function mbUnserialize($serial_str)
{
    // try to unserialize
    $return = unserialize($serial_str);
    return $return ? $return : unserialize(utf8_encode($serial_str));
}
/**
 * convert standard date in iso format eg. 01.12.1970 to 1970-12-01
 *
 *@param string $date date to convert
 *
 *@return string|bool return false if date is not a valid std.format
 */
function dateStdToIso($date)
{
    if (!preg_match('=\d{1,2}\.\d{1,2}\.\d{2,4}=', $date))
        return false;
    $temp = explode('.', $date);
    if (count($temp) != 3)
        return false;
    return (strlen($temp[2]) == 2 ? '20' . $temp[2] : $temp[2]) . '-' . $temp[1] . '-' . $temp[0];
}
/**
 * convert standard iso date in std format eg. 1970-12-01 to 01.12.1970
 *
 *@param string $date date to convert
 *
 *@return mixed return false if in date is not a valid std.format
 */
function dateIsoToStd($date)
{
    // strip may included time
    $date = preg_replace('=\s\d{2}:\d{2}:\d{2}$=', '', $date);
    if (!preg_match('=\d{4}-\d{1,2}-\d{1,2}=', $date))
        return false;
    $temp = explode('-', $date);
    if (count($temp) != 3)
        return false;
    return $temp[2] . "." . $temp[1] . "." . $temp[0];
}
/**
 * convert standard iso date in unix time stamp format eg. 1970-12-01 to 15672376823
 *
 *@param string $date date to convert
 *
 *@return mixed return false if in date is not a valid std.format
 */
function dateIsoToStamp($date)
{
    // strip may included time
    $date = preg_replace('=\s\d{2}:\d{2}:\d{2}$=', '', $date);
    if (!preg_match('=\d{4}-\d{1,2}-\d{1,2}=', $date))
        return false;
    $temp = explode('-', $date);
    if (count($temp) != 3)
        return false;
    return mktime(0, 0, 0, $temp[1], $temp[2], $temp[0]);

}
/**
 * split a set of words
 *
 * @param string $xstr     input string
 * @param int    $xlenint  string len max
 * @param string $xlaststr continue string e.g. ...
 *
 * @return string cuted string
 */
function phpmyWordWrap($xstr, $xlenint, $xlaststr)
{
    if (mb_strlen($xstr, 'UTF-8') <= $xlenint)
        return $xstr;
    $return = mb_substr($xstr, 0, $xlenint - mb_strlen($xlaststr, 'UTF-8'), 'UTF-8') . $xlaststr;
    return $return;
}
/**
 * return web url path, for base tags
 *
 * @param bool $b_includeparamter include url paramater, default = false
 *
 * @return string
 */
function getRequestPath($b_includeparamter = false)
{
    $url = (string) null;
    switch ($_SERVER['SERVER_PORT'])
    {
        case '443':
            $url .= 'https://';
            break;
        case '80':
        default:
            $url .= 'http://';
            break;
    }
    $url .= $_SERVER['SERVER_NAME'];
    $url .= getRequestFile();
    if ($b_includeparamter)
        $url .= '?' . getUpdatedRequestParamter();
    return $url;
}
/**
 * modified getRequestParamter(), it returns may updated parameter
 *
 * @return string
 */
function getUpdatedRequestParamter()
{
    $tmp = null;
    foreach ($_GET as $k=>$v)
    {
        $tmp .= ($tmp ? '&' : '') . $k . '=' . urlencode($v);
    }
    return $tmp;
}
/**
 * return request file name
 *
 * @return string
 */
function getRequestFile()
{
    return (
        stripos($_SERVER['REQUEST_URI'], '?') ?
            substr($_SERVER['REQUEST_URI'], 0, stripos($_SERVER['REQUEST_URI'], '?'))
            : $_SERVER['REQUEST_URI']
    );
}
/**
 * return url get parameter
 *
 * @return string
 */
function getRequestParamter()
{
    return $_SERVER['QUERY_STRING'];
}
/**
 * read supported language from browser
 *
 * @param array $allowed_languages accepted language e.g. de, en, ...
 *
 * @return string supported languages e.g. de
 */
function getBrowserLanguage($allowed_languages = array())
{
    $lang_variable = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
    // split header
    $accepted_languages = preg_split('/,\s*/', $lang_variable);
    foreach ($accepted_languages as $accepted_language)
    {
        // Alle Infos über diese Sprache rausholen
        $res = preg_match(
            '/^([a-z]{1,8}(?:-[a-z]{1,8})*)'
            . '(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', $accepted_language, $matches
        );
        // valid
        if (!$res)
            continue;
        // get lang. code and split
        $lang_code = explode('-', $matches[1]);
        // qualitiy included?
        if (isset ($matches[2]))
            $lang_quality = (float) $matches[2];
        else
            $lang_quality = 1.0;
        // do till empty
        while (count($lang_code))
        {
            // within allowed lanuages
            if (in_array(strtolower(join('-', $lang_code)), $allowed_languages))
                return strtolower(join('-', $lang_code));
            // cut right side
            array_pop($lang_code);
        }
    }
    return array();
}
/**
 * returns (die()) file content with a nice Expire Header
 *
 * @param string $localfile local file resource
 *
 * @return void die's ever and set a header
 */
function getHeaderCachedLocalFile($localfile = null)
{
    if (!$localfile || !file_exists($localfile))
        die (header('HTTP/1.1 404 Not Found'));
    $last_modified_time = filemtime($localfile);
    $etag = md5_file($localfile);

    $s_ifModifSince = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : 0;
    $s_ifNoneMatch = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? $_SERVER['HTTP_IF_NONE_MATCH'] : '';
    if (strtotime($s_ifModifSince) == $last_modified_time
        || trim($s_ifNoneMatch) == $etag
    )
    {
        die (header("HTTP/1.1 304 Not Modified"));
    }
    $i_cacheDuration = 20;
    $i_len = filesize($localfile);
    header('Content-Length: ' . $i_len);
    header('Expires: Thu, 19 Nov 2200 08:52:00 GMT');
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_modified_time).' GMT');
    header('Etag: "' . $etag .'"');
    header('Pragma: public');
    header('Cache-Control: public, max-age=' . ($i_cacheDuration * 60));
    header('Cache-Control: pre-check=' . ($i_cacheDuration * 60), false);
    $mimetype = 'text/plain';
    $s_ext = preg_replace('=^(.*\.)=', '', strtolower($localfile));
    $mT = getMimeTypeArray();
    if (in_array($s_ext, array_keys($mT)))
    {
        $mimetype = $mT[$s_ext];
    }
    else
    {
        if (function_exists('mime_content_type'))
            $mimetype = mime_content_type($localfile);
        else
            $mimetype = 'unknown';
    }
    header('content-type: ' . $mimetype . '; charset=utf-8');
    die (readfile($localfile));
}
/**
 * return array with known mime type
 *
 * @return array
 */
function getMimeTypeArray ()
{
    $mime_types = array(
        'txt' => 'text/plain',
        'htm' => 'text/html',
        'html' => 'text/html',
        'php' => 'text/html',
        'css' => 'text/css',
        'js' => 'application/javascript',
        'json' => 'application/json',
        'xml' => 'application/xml',
        'swf' => 'application/x-shockwave-flash',
        'flv' => 'video/x-flv',

        // images
        'png' => 'image/png',
        'jpe' => 'image/jpeg',
        'jpeg' => 'image/jpeg',
        'jpg' => 'image/jpeg',
        'gif' => 'image/gif',
        'bmp' => 'image/bmp',
        'ico' => 'image/vnd.microsoft.icon',
        'tiff' => 'image/tiff',
        'tif' => 'image/tiff',
        'svg' => 'image/svg+xml',
        'svgz' => 'image/svg+xml',

        // archives
        'zip' => 'application/zip',
        'rar' => 'application/x-rar-compressed',
        'exe' => 'application/x-msdownload',
        'msi' => 'application/x-msdownload',
        'cab' => 'application/vnd.ms-cab-compressed',

        // audio/video
        'mp3' => 'audio/mpeg',
        'qt' => 'video/quicktime',
        'mov' => 'video/quicktime',

        // adobe
        'pdf' => 'application/pdf',
        'psd' => 'image/vnd.adobe.photoshop',
        'ai' => 'application/postscript',
        'eps' => 'application/postscript',
        'ps' => 'application/postscript',

        // ms office
        'doc' => 'application/msword',
        'rtf' => 'application/rtf',
        'xls' => 'application/vnd.ms-excel',
        'ppt' => 'application/vnd.ms-powerpoint',

        // open office
        'odt' => 'application/vnd.oasis.opendocument.text',
        'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
    );
    return $mime_types;
}